package com.hl.im.gateway.router;

import com.alibaba.fastjson.JSON;
import com.alibaba.nacos.api.config.listener.Listener;
import com.alibaba.nacos.api.exception.NacosException;
import com.hl.im.gateway.config.GatewayConfig;
import com.hl.im.gateway.config.NacosConfig;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.cloud.gateway.route.RouteDefinition;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.Executor;

/**
 * @author huanglin
 * @apiNote
 * @date: 2023/10/07 17:26
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class DynamicRouterByNacosService implements CommandLineRunner {

    private final NacosConfig config;
    private final DynamicRouteService dynamicRouteService;
    private final GatewayConfig gatewayConfig;

    @Override
    public void run(String... args) throws Exception {
        String routeConfig = config.getRouteConfig();
        log.info("动态更新路由配置 config {}",routeConfig);
        // 初始化
        List<RouteDefinition> definitionList = JSON.parseArray(routeConfig, RouteDefinition.class);
        for (RouteDefinition routeDefinition : definitionList) {
            dynamicRouteService.add(routeDefinition);
        }

        dynamicRouteByNacosListener(gatewayConfig.getNACOS_ROUTE_DATA_ID(), gatewayConfig.getNACOS_ROUTE_GROUP());
    }


    /**
     * 监听Nacos下发的动态路由配置
     *
     * @param dataId
     * @param group
     */
    public void dynamicRouteByNacosListener(String dataId, String group) {
        try {
            config.getConfigService().addListener(dataId, group, new Listener() {
                @Override
                public void receiveConfigInfo(String configInfo) {
                    log.info("进行网关更新:\n\r{}", configInfo);
                    List<RouteDefinition> definitionList = JSON.parseArray(configInfo, RouteDefinition.class);
                    log.info("update route : {}", definitionList.toString());
                    dynamicRouteService.updateList(definitionList);
                }

                @Override
                public Executor getExecutor() {
                    log.info("getExecutor\n\r");
                    return null;
                }
            });
        } catch (NacosException e) {
            log.error("从nacos接收动态路由配置出错!!!", e);
        }
    }
}
